importScripts('https://cdnjs.cloudflare.com/ajax/libs/mathjs/11.5.0/math.js')

self.onmessage = ({ data }) => {
  try {
    const fn = math.compile(data.expression)
    const scope = {}

    // Build dependency chain
    data.dependencies.forEach(([depId, depCode]) => {
      scope[depId] = math.compile(depCode)
    })

    // Create evaluation function
    const evaluator = (x, y) => {
      const localScope = { x, y, ...scope }
      return fn.evaluate(localScope)
    }

    self.postMessage({
      id: data.id,
      evaluator: evaluator.toString(),
    })
  }
  catch (error) {
    self.postMessage({
      id: data.id,
      error: error.message,
    })
  }
}
